package _5thread;

import java.util.concurrent.locks.StampedLock;

/**
 * @Description:
 * @Author wangzhen
 * @Date 2022-06-21 22:40
 **/
public class StampedLockTest {


    public static void main(String[] args) throws InterruptedException {
        StampedLock lock=new StampedLock();

        new Thread(() -> {


            long version = lock.tryOptimisticRead();

            System.out.println(Thread.currentThread().getName()+"读取完成"+version);
//            try {
//                Thread.sleep(2000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }

            if(lock.validate(version)){
                System.out.println(Thread.currentThread().getName()+"无脏读,结束"+version);
                return;

            }else{
                long readLock = lock.readLock();
                System.out.println(Thread.currentThread().getName()+"版本号不一致,切换悲观锁"+readLock);
                try {

                }finally {
                    lock.unlockRead(readLock);
                }
            }



        },"t1").start();


        Thread.sleep(200);
        new Thread(() -> {

            long writeLock = lock.writeLock();
            System.out.println(Thread.currentThread().getName()+"写入完成"+writeLock);
            lock.unlockWrite(writeLock);
//            long readLock = lock.readLock();
//            System.out.println(Thread.currentThread().getName()+"读完成"+readLock);
//            lock.unlockRead(readLock);

        },"t2").start();

    }
}
